<?php

namespace App\Admin\Controllers;

use App\Models\AdminUser;
use Dcat\Admin\Auth\Permission;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\IFrameGrid;
use Dcat\Admin\Models\Administrator as AdministratorModel;
use Dcat\Admin\Models\Repositories\Administrator;
use Dcat\Admin\Show;
use Dcat\Admin\Support\Helper;
use Dcat\Admin\Widgets\Tree;
use Dcat\Admin\Controllers\UserController as BaseUserController;
use Dcat\Admin\Admin;
use Large\Zhengdada\Functions;


class UserController extends BaseUserController
{
    public function title()
    {
        return trans('admin.administrator');
    }

    protected function grid()
    {
        return Grid::make(new Administrator('roles'), function (Grid $grid) {
            $grid->setActionClass(Grid\Displayers\ContextMenuActions::class);

            $grid->model()->orderBy('id', 'desc');
            $grid->model()->whereHas('roles', function ($q) {
                $q->where('id', '!=', 2);
            });
            //$grid->id('ID')->sortable();
            $grid->username;
            $grid->name;


            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $rows  = $actions->row;
                $token = @csrf_token();

                $res['username'] = $rows->username;
                $res['password'] = $rows->password;
                $res['_token']   = $token;
                $res             = json_encode($res);

                // append一个操作
                //$actions->append('<a class="denru" ><i class="fa fa-eye"></i>登陆</a>');
                Admin::script(
                    <<<JS
                        $('.denru').on('click', function(){
                            $.ajax({
                                url: '/member/auth/login',
                                type: 'post',
                                data: $res,
                                success:function(res){
                                    location.href = '/member/auth/login';
                                }
                            })
                        });
JS
                );
            });

            //decrypt($value);

            if (config('admin.permission.enable')) {
                $grid->roles->pluck('name')->label('primary', 3);

                $permissionModel = config('admin.database.permissions_model');
                $roleModel       = config('admin.database.roles_model');

                $nodes   = (new $permissionModel())->allNodes();
                $newData = Functions::getTreeData($nodes, 7, 'parent_id');

                foreach ($nodes as $k => &$v) {
                    if (in_array($v['id'], collect($newData)->pluck('id')->toArray()) || $v['id'] == 7) {
                        unset($nodes[$k]);
                    }
                }

                $grid->permissions
                    ->if(function () {
                        return !empty($this->roles);
                    })
                    ->showTreeInDialog(function (Grid\Displayers\DialogTree $tree) use (&$nodes, $roleModel) {
                        $tree->nodes($nodes);

                        foreach (array_column($this->roles, 'slug') as $slug) {
                            if ($roleModel::isAdministrator($slug)) {
                                $tree->checkAll();
                            }
                        }
                    })
                    ->else()
                    ->emptyString();
            }

            $grid->phone;
            $grid->email;
            //$grid->is_lock(trans('admin-user.fields.is_lock'))->switch();
            $grid->created_at->sortable();
            //$grid->updated_at->sortable();

            $grid->quickSearch(['id', 'name', 'username']);

            $grid->disableBatchDelete();
            $grid->showQuickEditButton();
            $grid->disableFilterButton();
            $grid->enableDialogCreate();

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if ($actions->getKey() == AdministratorModel::DEFAULT_ID && Admin::user()->id != AdministratorModel::DEFAULT_ID) {
                    $actions->disableDelete();
                    $actions->disableQuickEdit();
                    $actions->disableEdit();
                }
            });
        });
    }

    protected function iFrameGrid()
    {
        $grid = new IFrameGrid(new Administrator());

        $grid->quickSearch(['id', 'name', 'username']);

        $grid->id->sortable();
        $grid->username;
        $grid->name;
        $grid->created_at;

        return $grid;
    }


    protected function detail($id)
    {
        return Show::make($id, new Administrator('roles'), function (Show $show) use ($id) {
            // 验证是不是管理员, 是往下
            verifyUserRole($id);
            $show->disableDeleteButton();

            $show->username;
            $show->name;
            //$show->avatar(__('admin.avatar'))->image();
            if (config('admin.permission.enable')) {
                $show->roles->as(function ($roles) {
                    if (!$roles) {
                        return;
                    }
                    return collect($roles)->pluck('name');
                })->label();

                $show->permissions->unescape()->as(function () {
                    $roles = (array) $this->roles;

                    $permissionModel = config('admin.database.permissions_model');
                    $roleModel       = config('admin.database.roles_model');
                    $permissionModel = new $permissionModel();
                    $nodes           = $permissionModel->allNodes();
                    $newData         = Functions::getTreeData($nodes, 7, 'parent_id');

                    foreach ($nodes as $k => &$v) {
                        if (in_array($v['id'], collect($newData)->pluck('id')->toArray()) || $v['id'] == 7) {
                            unset($nodes[$k]);
                        }
                    }

                    $tree = Tree::make($nodes);

                    $isAdministrator = false;
                    foreach (array_column($roles, 'slug') as $slug) {
                        if ($roleModel::isAdministrator($slug)) {
                            $tree->checkAll();
                            $isAdministrator = true;
                        }
                    }

                    if (!$isAdministrator) {
                        $keyName = $permissionModel->getKeyName();
                        $tree->check(
                            $roleModel::getPermissionId(array_column($roles, $keyName))->flatten()
                        );
                    }

                    return $tree->render();
                });
            }

            $show->created_at;
            //$show->updated_at;
        });
    }

    public function form()
    {
        return Form::make(new Administrator('roles'), function (Form $form) {

            $userTable  = config('admin.database.users_table');
            $connection = config('admin.database.connection');
            $id         = $form->getKey();
            $form->disableDeleteButton();

            if (request()->path() != "hdcrm/auth/users/create") {
                // 验证是不是管理员, 是往下
                verifyUserRole($id);
            }

            $form->text('username', trans('admin.username'))
                ->required()
                ->creationRules(['required', "unique:{$connection}.{$userTable}"])
                ->updateRules(['required', "unique:{$connection}.{$userTable},username,$id"]);
            $form->text('name', trans('admin.name'))->required();
            //$form->image('avatar', trans('admin.avatar'))->autoUpload();

            if ($id) {
                $form->password('password', trans('admin.password'))
                    ->minLength(5)
                    ->maxLength(20)
                    ->customFormat(function () {
                        return '';
                    });
                $form->password('pay_password', trans('admin.pay_password'))
                    ->minLength(5)
                    ->maxLength(20)
                    ->customFormat(function () {
                        return '';
                    });
            } else {
                $form->password('password', trans('admin.password'))
                    ->required()
                    ->minLength(5)
                    ->maxLength(20);
                $form->password('pay_password', trans('admin.pay_password'))
                    ->required()
                    ->minLength(5)
                    ->maxLength(20);
            }

//            $form->password('password_confirmation', trans('admin.password_confirmation'))->same('password');

            $form->ignore(['password_confirmation']);

            if (config('admin.permission.enable')) {
                $form->multipleSelect('roles', trans('admin.roles'))
                    ->options(function ($form) {
                        $roleModel = config('admin.database.roles_model');

                        $roles = $roleModel::all()->pluck('name', 'id');

                        if (Admin::user()->id != AdministratorModel::DEFAULT_ID) {
                            \Arr::forget($roles, 1);
                        }
                        \Arr::forget($roles, 2);
                        return $roles;
                    })
                    ->customFormat(function ($v) {
                        return array_column($v, 'id');
                    })->required();
            }

            $form->radio('is_lock', trans('admin-user.fields.is_lock'))->options(['0' => '锁定', '1' => '正常']);
            $form->display('created_at', trans('admin.created_at'));
            $form->hidden('dry_password');
            $form->hidden('profit_rate');

            if ($id == AdministratorModel::DEFAULT_ID) {
                $form->disableDeleteButton();
            }

            $form->saving(function (Form $form) use ($id) {
                // 验证是不是管理员, 是往下
                if (request()->path() != "hdcrm/auth/users") {
                    if (!verifyUserRole($id, false)) {
                        return $form->error('参数错误, 不可修改');
                    }
                }

                $form->profit_rate = 50;
                if ($form->password && $form->model()->get('password') != $form->password) {
                    $form->dry_password = encrypt(config('app.dry_passwork').$form->password);
                    $form->password     = bcrypt($form->password);
                }
                if (!array_filter($form->roles)) {
                    return $form->error('角色必选一个');
                }
                if (!$form->password) {
                    $form->deleteInput('password');
                }
            });
        });
    }

    public function destroy($id)
    {
        if (in_array(AdministratorModel::DEFAULT_ID, Helper::array($id))) {
            Permission::error();
        }

        // 验证是不是管理员, 是往下
        if (!verifyUserRole($id)) {
            return Admin::script(
                <<<JS
                Dcat.error('参数错误');
JS
            );
        }

        return parent::destroy($id);
    }
}
